package com.smedi.ismedi.personnel.core.domain.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.smedi.ismedi.personnel.core.domain.aggregatemodel.ProfileImage;
import com.smedi.ismedi.personnel.core.domain.repository.ProfileImageRepository;
import com.smedi.ismedi.personnel.core.domain.repository.ProfileImageTemporaryRepository;
import com.smedi.ismedi.personnel.core.domain.service.ProfileImageDomainService;
import com.smedi.ismedi.personnel.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.personnel.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.personnel.core.infrastructure.enumerate.CapacityEnum;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: xulinjun
 * @Date: 2021-6-9 14:00
 */
@Slf4j
@Service
@AllArgsConstructor
public class ProfileImageDomainServiceImpl implements ProfileImageDomainService {
    private final ProfileImageRepository profileImageRepository;

    private final ProfileImageTemporaryRepository profileImageTemporaryRepository;

    @Override
    public Boolean validateImageSize(Long len, int size, CapacityEnum capacity) {
        double fileSize = 0;
        if (CapacityEnum.BYTE.equals(capacity)) {
            fileSize = (double) len;
        } else if (CapacityEnum.KB.equals(capacity)) {
            fileSize = (double) len / 1024;
        } else if (CapacityEnum.MB.equals(capacity)) {
            fileSize = (double) len / 1048576;
        } else if (CapacityEnum.GB.equals(capacity)) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean isImage(MultipartFile file) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String fileNameOriginal = file.getOriginalFilename();
        String mimeType = request.getServletContext().getMimeType(fileNameOriginal);
        return mimeType.startsWith("image/");
    }

    @Override
    public ProfileImage saveProfileImage(String imageUUID, Long personId) {
        boolean exist = true;
        // 判断当前人员是否有照片
        ProfileImage profileImage = profileImageRepository.selectProfileImageByPersonId(personId);
        if (profileImage == null) {
            profileImage = new ProfileImage().setPersonId(personId);
            exist = false;
        }

        // 如果不是一致的id，说明被更新过了，则执行保存数据
        if (!imageUUID.equals(profileImage.getUuid())) {
            String tempPathPattern = ConstantField.profileImageTempPath + imageUUID; // 临时文件地址

            // 获取服务器上存储的路径
            List<String> keys = profileImageTemporaryRepository.checkProfileImageTemporaryIsExist(tempPathPattern);
            if (keys.size() > 0) {
                String key = keys.get(0);
                StorePath storePath = profileImageTemporaryRepository.getStorePathByKey(key);
                if (storePath != null) {
                    profileImage.setFileGroup(storePath.getGroup())
                            .setFilePath(storePath.getPath())
                            .setUuid(imageUUID);

                    profileImage = exist ? profileImageRepository.doUpdate(profileImage) : profileImageRepository.doInsert(profileImage);
                    profileImageTemporaryRepository.deleteProfileImageTemporary(key);
                } else {
                    throw LogicException.raise(CustomError.IMAGE_UUID_MISS);
                }
            } else {
                throw LogicException.raise(CustomError.IMAGE_UUID_MISS);
            }
        }

        return profileImage;
    }

    @Override
    public ProfileImage saveProfileImage(StorePath storePath, Long personId) {
        boolean exist = true;
        // 判断当前人员是否有照片
        ProfileImage profileImage = profileImageRepository.selectProfileImageByPersonId(personId);
        if (profileImage == null) {
            profileImage = new ProfileImage().setPersonId(personId);
            exist = false;
        }

        profileImage.setFileGroup(storePath.getGroup())
                .setFilePath(storePath.getPath())
                .setUuid(IdUtil.simpleUUID());

        profileImage = exist ? profileImageRepository.doUpdate(profileImage) : profileImageRepository.doInsert(profileImage);
        return profileImage;
    }

    @Override
    public ProfileImage getProfileImage(String imageUUID) {
        return profileImageRepository.selectProfileImageByImageUUID(imageUUID);
    }
}
